
const EXPIRE =7200;

class Cache {
	
	constructor(handler) {
		this.setHandler = uni.setStorageSync;
		this.getHandler = uni.getStorageSync;
		this.removeHandler = uni.removeStorageSync;
		this.p1ostfix = 'houjiji.paidai';
	}

	/**
	 * 设置缓存 
	 * @param  {[type]} k [键名]
	 * @param  {[type]} v [键值]
	 * @param  {[type]} t [时间、单位秒]
	 */
	set(k, v, t) {
		this.setHandler(k, v) 
		var seconds = parseInt(t);
		if (seconds > 0) {
			var timestamp = Date.parse(new Date());
			timestamp = timestamp / 1000 + seconds;
			this.setHandler(k + this.postfix, timestamp + "")
		} else {
			this.removeHandler(k + this.postfix)
		}
	}

	/**
	 * 获取缓存 
	 * @param  {[type]} k   [键名]
	 * @param  {[type]} def [获取为空时默认]
	 */
	get(k, def) {
		var deadtime = parseInt(this.getHandler(k + this.postfix)) 
		if (deadtime) {
			if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
				if (def) {
					return def;
				} else {
					return false;
				}
			}
		}
		var res = this.getHandler(k);
		if (res) {
			return res;
		} else {
			if (def == undefined  || def == "") {
				def = false; 
			}
			return def;
		}
	}
	/**
	 * 获取缓存 
	 * @param  {[type]} k   [键名]
	 * @param  {[type]} def [获取为空时默认]
	 */
	exists(k) {
		var deadtime = parseInt(this.getHandler(k + this.postfix)) 
		if (deadtime) {
			if (parseInt(deadtime) < Date.parse(new Date()) / 1000) {
				return false;
			}
		}
		var res = this.getHandler(k);
		if (res) {
			return true;
		} else {
			return false;
		}
	}

	remove(k) {
		this.removeHandler(k);
		this.removeHandler(k + this.postfix);
	}

	/**
	 * 清理所有缓存
	 * @return {[type]} [description]
	 */
	clear() {
		uni.clearStorageSync();
	}
}

const proxy = cache => { // 递归代理器
	return new Proxy(cache, {
		get(target, key) {  //代理get
			if (key in target){
				return target[key]
			}else{
				return target.get(key)
			}
		},
		set(target, key, value) {  //代理set
		    target.set(key,value);
			return true;
		},
		deleteProperty (target, key) { // 代理 delete
			target.remove(key);
			return true
		}
	})
}

export default proxy(new Cache);
